package com.example.app.components.MyModalBottomSheet.MyModalBottomSheetDateTimePicker

import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.width
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.SheetState
import androidx.compose.material3.SheetValue
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import com.example.app.cls.MyState
import com.example.app.components.MyButton.MyOutlinedSmallButton
import com.example.app.components.MyDatePicker.MyDatePicker
import com.example.app.components.MyIcon.MyDownIcon
import com.example.app.components.MyModalBottomSheet.MyModalBottomSheetCustomTopBarAndBottomBar
import com.example.app.components.MySpacer.MySpacer
import com.example.app.components.MyTimePicker.MyTimePicker
import com.example.app.ui.theme.formatDatePattern
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.TimeZone

class MyModalBottomSheetDateTimePickerState: MyState() {

}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyModalBottomSheetDateTimePicker(
    myModalBottomSheetDateTimePickerState: MyModalBottomSheetDateTimePickerState,
    myDateTimeSwitchBtnState: MyDateTimeSwitchBtnState,
    initDateTime: Long,
    onConfirm: (cal: Calendar) -> Unit
) {
    var scope = rememberCoroutineScope()
    //TimeZone.getTimeZone("Asia/Shanghai") 必须加，否则初始化的时间是前一天，会不准确
    var initCal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"))
    initCal.timeInMillis = initDateTime
    var visible = myModalBottomSheetDateTimePickerState.visible.collectAsState()
    //转到今天
    var turnToday by remember {
        mutableStateOf(false)
    }
    //转到今天按钮的显示或者隐藏
    var showTurnToday by remember {
        mutableStateOf(false)
    }
    //转到现在
    var turnNow by remember {
        mutableStateOf(false)
    }
    //转到现在的按钮，显示或者隐藏
    var showTurnNow by remember {
        mutableStateOf(false)
    }
    //屏幕宽度，做切换日期和时间的时候，横向滚动offsetX
    var windowWidth = with(LocalDensity.current) {
        LocalConfiguration.current.screenWidthDp
    }
    //这个是选择完后的cal，抛出去的
    var selectedCal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"))
    //显示bottomSheet
    if (visible.value) {
        //记录datepicker的height，因为timePicker的height和他不一样，做横向切换的时候，页面不稳定
        var datePickerHeight by remember {
            mutableStateOf(0)
        }
        //这个是bottomSheet的state
        var sheetState = SheetState(
            initialValue = SheetValue.Hidden,
            density = LocalDensity.current,
            skipPartiallyExpanded = true //这个初始化是为了，一打开就是全部高度，不用再滑到顶部，限制滑动到顶部
        )

        MyModalBottomSheetCustomTopBarAndBottomBar(
            sheetState = sheetState,
            onDismissRequest = {
                onConfirm(selectedCal)//抛出选择的日期
                myModalBottomSheetDateTimePickerState.flowUpdate_visible(false)
            },
            content = {
                var checked = myDateTimeSwitchBtnState.checked.collectAsState()
                //切换动画
                var offsetDatePicker =
                    animateDpAsState(targetValue = if (!checked.value) 0.dp else -windowWidth.dp)
                var offsetTimePicker =
                    animateDpAsState(targetValue = if (checked.value) 0.dp else -windowWidth.dp)
                //要用box，不然offsetX不起效果
                Box() {
                    Column(
                        modifier = Modifier
                            .offset(x = offsetDatePicker.value)
                            .width(windowWidth.dp)
                            .onGloballyPositioned {
                                if (it.size.height > datePickerHeight) datePickerHeight =
                                    it.size.height
                            },
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        //---------datePicker开始----------//
                        var datePickerState =
                            rememberDatePickerState(initDateTime)
                        //当前选中的日期
                        var selectedDatePickerCal =
                            Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"))
                        if (datePickerState != null && datePickerState.selectedDateMillis != null) {
                            //给当前选中的日期赋值
                            selectedDatePickerCal.timeInMillis =
                                datePickerState.selectedDateMillis!!
                            var selectedYear = selectedDatePickerCal.get(Calendar.YEAR)
                            var selectedMonth = selectedDatePickerCal.get(Calendar.MONTH)
                            var selectedDay = selectedDatePickerCal.get(Calendar.DAY_OF_MONTH)

                            selectedCal.set(
                                Calendar.YEAR,
                                selectedYear
                            )
                            selectedCal.set(
                                Calendar.MONTH,
                                selectedMonth
                            )
                            selectedCal.set(
                                Calendar.DAY_OF_MONTH,
                                selectedDay
                            )
                            var selectedFormat =
                                SimpleDateFormat(formatDatePattern).format(selectedDatePickerCal.timeInMillis)
                            var todayFormat =
                                SimpleDateFormat(formatDatePattern).format(Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai")).timeInMillis)
                            //如果当前选中的日期，不等于今天，则出现，回到今天
                            if ((selectedFormat != todayFormat) && offsetDatePicker.value >= 0.dp) {
                                showTurnToday = true
                            } else {
                                showTurnToday = false
                            }
                        }



                        MyDatePicker(state = datePickerState)
                        //回到今天，处理
                        if (turnToday) {
                            turnToday = false
                            var today = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"))
                            var todayYear = today.get(Calendar.YEAR)
                            var todayMonth = today.get(Calendar.MONTH)
                            var todayDay = today.get(Calendar.DAY_OF_MONTH)
                            selectedCal.set(
                                Calendar.YEAR,
                                todayYear
                            )
                            selectedCal.set(
                                Calendar.MONTH,
                                todayMonth
                            )
                            selectedCal.set(
                                Calendar.DAY_OF_MONTH,
                                todayDay
                            )
                            datePickerState.selectedDateMillis = selectedCal.timeInMillis
                        }
                    }
                    //---------datePicker结束----------//
                    //---------timePicker开始----------//
                    Column(
                        modifier = Modifier
                            .offset(x = offsetTimePicker.value)
                            .width(windowWidth.dp)
                            .height(with(LocalDensity.current) {
                                datePickerHeight.toDp() - 24.dp
                            }),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        MySpacer(modifier = Modifier.height(24.dp))
                        //回到现在，和回到今天，不一样的处理方式
                        //回到现在，不能给timePickerState直接赋值，所以，当回到今天的时候，需要重新初始化
                        var showTimePicker by remember {
                            mutableStateOf(true)
                        }

                        if (showTimePicker) {
                            var timePickerState =
                                rememberTimePickerState(
                                    initialHour = initCal.get(Calendar.HOUR_OF_DAY),
                                    initialMinute = initCal.get(Calendar.MINUTE),
                                    is24Hour = true
                                )
                            //给当前选中的时间，赋值
                            selectedCal.set(
                                Calendar.HOUR_OF_DAY,
                                timePickerState.hour
                            )
                            selectedCal.set(
                                Calendar.MINUTE,
                                timePickerState.minute
                            )
                            var nowCal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"))
                            var nowHour = nowCal.get(Calendar.HOUR_OF_DAY)
                            var nowMinute = nowCal.get(Calendar.MINUTE)
                            var selectedHour = selectedCal.get(Calendar.HOUR_OF_DAY)
                            var selectedMinute = selectedCal.get(Calendar.MINUTE)
                            //如果选中的时间，不是当前时间，则出现，回到现在的按钮
                            if ((nowHour != selectedHour || nowMinute != selectedMinute) && offsetTimePicker.value >= 0.dp) {
                                showTurnNow = true
                            } else {
                                showTurnNow = false
                            }

                            MyTimePicker(state = timePickerState)
                        }
                        //回到现在，处理
                        if (turnNow) {
                            initCal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"))
                            turnNow = false
                            showTimePicker = false
                            scope.launch {
                                delay(50)
                                showTimePicker = true
                            }
                        }
                    }
                    //---------timePicker结束----------//
                }
            },
            topBarTitle = {
                //切换，日期，时间 switch
                MyDateTimeSwitchBtn(myDateTimeSwitchBtnState = myDateTimeSwitchBtnState)
            },
            topBarActions = {
                //回到今天
                if (showTurnToday) {
                    MyOutlinedSmallButton(
                        onClick = {
                            turnToday = true
                        },
                        text = "今天"
                    )
                }
                //回到现在
                if (showTurnNow) {
                    MyOutlinedSmallButton(
                        onClick = {
                            turnNow = true
                        },
                        text = "现在"
                    )
                }
            },
            topNavigationIcon = {
                MyDownIcon(modifier = Modifier.clickable {
                    myModalBottomSheetDateTimePickerState.flowUpdate_visible(false)
                })
            },
        )
    }
}